package com.tanhua.server.server;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;


import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessageService {
    @DubboReference
    private FriendsApi friendsApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    //添加联系人
    public void contacts(Long userId) {
        //1.把好友关系写入到mongodb
        Long nowId = UserHolder.getUserId();
        friendsApi.save(userId,nowId);
        //2.把好友关系写入环信
        huanXinTemplate.addContact("hx"+userId,"hx"+nowId);//添加好友的环信用户
    }
   //获取联系人列表
    public PageResult friendPage(Integer page, Integer pageSize) {
        Long userId = UserHolder.getUserId();
        //此处不能直接获取userInfo，friend在mongo库 info在mysql库，要在这里查userinfo
       List<Friend> list = friendsApi.friendPage(userId,page,pageSize);
       if (CollUtil.isEmpty(list)){
           return new PageResult();
       }
       //防止一个一个id得查找，获取所有id
       List<Long> ids = CollUtil.getFieldValues(list,"friendId",Long.class);
       //获取所有好友信息
        Map<Long, UserInfo> map = userInfoApi.findIds(ids);
        List<ContactVo> contactVos = new ArrayList<>();
        for (Friend friend : list) {
            Long friendId = friend.getFriendId();
            //获取好友得id，通过id在map集合中查找对应得userinfo
            UserInfo userInfo = map.get(friendId);
            ContactVo vo = ContactVo.init(userInfo);
            contactVos.add(vo);
        }

        return new PageResult(page,pageSize,0l,contactVos);
    }
}
